package ddz;

import java.util.Arrays;
import java.util.Random;

public class Game {

    private Pkp[] initPkp = new Pkp[54];//初始化54张牌
    private Player[] players = new Player[3];//初始化3个玩家

    public Game(Player[] players){
        if (players.length != 3){
            System.out.println("玩家最多只能有三个");
            System.exit(0);
        }
        this.players = players;
        init();//初始化pkp

    }
        private void init(){

        int index = 0;
            for (PkpStyle style : PkpStyle.values()){

                for (int i = 3; i<= 15; i ++){ //大小王不能在循环内
                    Pkp pkp = new Pkp(i,style);
                    initPkp[index] = pkp;
                    index ++;
                }
            }
            Pkp xiaogui = new Pkp(16,null);
            Pkp dagui = new Pkp(17,null);
            initPkp[initPkp.length - 2] = xiaogui;
            initPkp[initPkp.length - 1] = dagui;

        }


        public void start(){
        for (int i = 0; i < 17; i ++){
            //最多循环17次，把牌分完
            for (Player player : this.players){
                Random r = new Random();
                int index = r.nextInt(initPkp.length);
                player.getPkps()[i] = initPkp[index];
                //删除发出去的牌
                initPkp[index] = initPkp[initPkp.length - 1];
                Pkp[] newpkp = new Pkp[initPkp.length - 1];
                newpkp = Arrays.copyOf(initPkp,initPkp.length - 1);
                initPkp = newpkp;
                }
            }

        Random r = new Random();
        int index = r.nextInt(players.length);
        players[index].setDizhu(true);

        int plen = players[index].getPkps().length;
        players[index].getPkps()[plen-3] = initPkp[initPkp.length - 3];
            players[index].getPkps()[plen-3] = initPkp[initPkp.length - 2];
            players[index].getPkps()[plen-3] = initPkp[initPkp.length - 1];

            paixu();

        }


        private void paixu(){
        for (Player player : players){
            for (int i = 0; i < player.getPkps().length; i++){
                for (int j = i + 1; j < player.getPkps().length; j++){
                    if (player.getPkps()[i] != null && player.getPkps()[j] != null){
                        if (player.getPkps()[i].getRealvalue() > player.getPkps()[j].getRealvalue()){
                            Pkp temp = player.getPkps()[i];
                            player.getPkps()[i] = player.getPkps()[j];
                            player.getPkps()[j] =temp;
                        }
                    }

                }
            }
        }
        }

    public Pkp[] getInitPkp() {
        return initPkp;
    }
}
